package com.inyourcode.core.db.iml;

import com.inyourcode.core.db.api.IDBResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author JackLei
 */
public class RedisResource implements IDBResource {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisResource.class);
    private RedisTemplate<String, byte[]> redisTemplate;
    private HashOperations<String, String, byte[]> hashOperations;

    public RedisResource(RedisTemplate<String, byte[]> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
    }

    @Override
    public Map<String, byte[]> load(String key) {
        return this.hashOperations.entries(key);
    }

    @Override
    public void save(String key, Map<String, byte[]> updateDatas) {
        for (Map.Entry<String, byte[]> entry : updateDatas.entrySet()) {
            String subKey = entry.getKey();
            byte[] data = entry.getValue();
            this.hashOperations.put(key, subKey, data);
        }
    }

    public void cacheDataOptExpire(boolean clear, String key, int expireTime) {
        if (clear) {
            LOGGER.info("[{}]Data expiration time is:{}", key, expireTime);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        } else {
            LOGGER.info("[{}]Cancel Data expiration", key);
            redisTemplate.persist(key);
        }
    }
}
